package com.hnevc.androidui9;

import android.util.Xml;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/6/21.
 */

public class WeatherService {
    public static List<WeatherInfo> getInfosFromXML(InputStream is)
            throws XmlPullParserException, IOException {
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(is, "utf_8");
        List<WeatherInfo> weatherInfos = null;
        WeatherInfo weatherInfo = null;

        int type = parser.getEventType();
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
                case XmlPullParser.START_TAG:
                    if (parser.getName().equals("infos")) {
                        weatherInfos = new ArrayList<>();
                    }
                    if (parser.getName().equals("city")) {
                        weatherInfo = new WeatherInfo();
                        String id =parser.getAttributeValue(0);
                        weatherInfo.setId(id);
                    }
                    if (parser.getName().equals("temp")) {
                        String temp = parser.nextText();
                        weatherInfo.setTemp(temp);
                    }
                    if (parser.getName().equals("name")){
                        String name =parser.nextText();
                        weatherInfo.setName(name);
                    }
                    if (parser.getName().equals("weather")){
                        String weather =parser.nextText();
                        weatherInfo.setWeather(weather);
                    }
                    if (parser.getName().equals("pm")){
                        String pm =parser.nextText();
                        weatherInfo.setPm(pm);
                    }
                    if (parser.getName().equals("wind")){
                        String wind =parser.nextText();
                        weatherInfo.setWind(wind);
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if (parser.getName().equals("city")) {
                        weatherInfos.add(weatherInfo);
                    }
                    break;
            }
            type = parser.next();
        }
        return weatherInfos;

    }
}
